// src/api/safety/inspectionDetail.ts
import { http } from "@/utils/http";
import {IEditorConfig, IToolbarConfig} from "@wangeditor/editor";

/** 分页查询参数 */
export interface InspectionListCommand extends BasePageQuery {
  inspectionName?: string; // 用于 like 搜索
  deptId?: number; // 部门 ID
  startTime?: string; // 计划日期开始时间
  endTime?: string; // 计划日期结束时间
  status?: string; // 状态
  createBy?: string; // 用于 like 搜索
  inspectionType?: string; // 新增检查类型查询参数
}

/** 检查计划DTO */
export interface InspectionPageResponse {
  inspectionId: number;
  inspectionName: string;
  inspectionSource: string;
  startTime: string;
  endTime: string;
  inspectionContent: string;
  inspectionDeptId: number;
  createBy: string;
  createTime: string;
  updateBy: string;
  updateTime: string;
  remark: string;
  status: string;
  planDate: string;
  inspectionCode: string;
  checkCount: number;
  checkOkCount: number;
  inspectionType: string;
  inspectionPeriod: string;
  inspectionLevel: string;
  approver: number;
  deptId: number;
  checkUseridList: string;
  checkUserId: number;
  creatorId: number;
  updaterId: number;
  deleted: boolean;
  deptName: string; // 新增字段
  userNameList: string[]; // 新增字段
  checkItemCount: number; // 新增检查项目数量字段
  checkProgress: number; // 新增检查进度字段
}

/** 获取检查计划列表 */
export const getInspectionListApi = (params: InspectionListCommand) => {
  return http.request<ResponseData<PageDTO<InspectionPageResponse>>>(
    "get",
    "/safety/inspection/list",
    {
      params
    }
  );
};

/** 导出检查计划Excel */
export const exportInspectionExcelApi = (
  params: InspectionListCommand,
  fileName: string
) => {
  return http.download("/safety/inspection/excel", fileName, {
    params
  });
};

/** 删除检查计划 */
export const deleteInspectionApi = (data: Array<number>) => {
  return http.request<ResponseData<void>>("delete", "/safety/inspection", {
    params: {
      ids: data.toString()
    }
  });
};

/** 新增检查计划 */
export interface AddInspectionCommand {
  inspectionName: string;
  inspectionSource?: string;
  startTime?: string;
  endTime?: string;
  inspectionContent?: string;
  inspectionDeptId?: number;
  createBy?: string;
  createTime?: string;
  updateBy?: string;
  updateTime?: string;
  remark?: string;
  status?: string;
  planDate?: string;
  inspectionCode?: string;
  checkCount?: number;
  checkOkCount?: number;
  inspectionType?: string;
  inspectionPeriod?: string;
  inspectionLevel?: string;
  approver?: number;
  deptId?: number;
  checkUseridList?: string;
  checkUserId?: number;
  creatorId?: number;
  updaterId?: number;
  deleted?: boolean;
  type?: string;
  // 新增驳回意见字段
  suggestion?: string;
}

// 定义用户信息类型
export interface UserInfo {
  creatorId: null | number;
  createTime: string;
  updaterId: null | number;
  updateTime: string;
  deleted: boolean;
  userId: number;
  postId: null | number;
  roleId: null | number;
  deptId: number;
  username: string;
  nickname: string;
  userType: number;
  email: string;
  phoneNumber: string;
  sex: number;
  avatar: string;
  password: string;
  status: number;
  loginIp: string;
  loginDate: null | string;
  isAdmin: boolean;
  remark: null | string;
}

export interface ApiResponse {
  code: number;
  msg: string;
  data: UserInfo[];
}

// 类型断言函数，确保返回数据类型正确
export const assertApiResponse = (data: any): data is ApiResponse => {
  return typeof data.code === 'number' && typeof data.msg === 'string' && Array.isArray(data.data);
};


/** 修改检查计划 */
export interface UpdateInspectionCommand extends AddInspectionCommand {
  inspectionId: number;
}

export const addInspectionApi = (data: AddInspectionCommand) => {
  // 简单校验必填字段
  if (!data.inspectionName) {
    throw new Error("检查名称不能为空");
  }
  return http.request<ResponseData<void>>("post", "/safety/inspection", {
    data
  });
};

export const updateInspectionApi = (data: UpdateInspectionCommand) => {
  // 简单校验必填字段
  if (!data.inspectionName || !data.inspectionId) {
    throw new Error("检查名称和检查计划 ID 不能为空");
  }
  return http.request<ResponseData<void>>("put", "/safety/inspection", {
    data
  });
};

/** 获取检查计划详情 */
export const getInspectionInfoApi = (inspectionId: string) => {
  return http.request<ResponseData<InspectionPageResponse>>(
    "get",
    `/safety/inspection/${inspectionId}`
  );
};


/**
 * 将 HTML 富文本内容编码为 Base64（UTF-8）
 */
export function encodeHtmlToBase64(html: string): string {
  const utf8Bytes = new TextEncoder().encode(html); // 使用 UTF-8 编码
  const binaryString = Array.from(utf8Bytes)
    .map(byte => String.fromCharCode(byte))
    .join("");
  return btoa(binaryString); // 转为 base64
}

export function decodeBase64(base64Str: string): string {
  try {
    return decodeURIComponent(
      atob(base64Str)
        .split("")
        .map(function (c) {
          return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
        })
        .join("")
    );
  } catch (err) {
    return "<p>内容解析失败</p>";
  }
}

export const editorConfig: Partial<IEditorConfig> = {
  hoverbarKeys: {
    attachment: {
      menuKeys: ['downloadAttachment'], // “下载附件”菜单
    },
  },
  // TS 语法
  MENU_CONF: {
    uploadAttachment: {
      server: 'https://airport.dingyangmy.cn/prod-api/file/uploadRichText', // 服务端地址
      timeout: 5 * 1000, // 5s

      fieldName: 'custom-fileName',
      // meta: {token: 'xxx', a: 100}, // 请求时附加的数据
      metaWithUrl: true, // meta 拼接到 url 上
      headers: {Accept: 'text/x-json'},

      maxFileSize: 10 * 1024 * 1024, // 10M

      onBeforeUpload(file: File) {
        console.log('onBeforeUpload', file)
        return file // 上传 file 文件
        // return false // 会阻止上传
      },
      onProgress(progress: number) {
        console.log('onProgress', progress)
      },
      onSuccess(file: File, res: any) {
        console.log('onSuccess', file, res)
      },
      onFailed(file: File, res: any) {
        alert(res.message)
        console.log('onFailed', file, res)
      },
      onError(file: File, err: Error, res: any) {
        alert(err.message)
        console.error('onError', file, err, res)
      },
    },

    uploadImage: {
      // 上传接口地址，必须是完整地址（你本地 Node 服务地址）
      server: 'https://airport.dingyangmy.cn/prod-api/file/uploadImage', // 服务端地址

      // 后端接收的字段名，对应 `formidable` 接收的字段
      fieldName: 'file',

      // 文件限制
      maxFileSize: 2 * 1024 * 1024, // 2MB
      allowedFileTypes: ['image/*'],

      // 设置 headers 和跨域选项（如果需要）
      headers: {
        Accept: 'application/json'
      },
      withCredentials: false,

      // 上传成功后的处理（可选）
      onSuccess(file, res) {
        console.log('上传成功:', res)
      },

      onFailed(file, res) {
        console.error('上传失败:', res)
      },

      onError(file, err, res) {
        console.error('上传出错:', err)
      },
    }
  }
}


export const editorConfig1: Partial<IEditorConfig> = {
  hoverbarKeys: {
    attachment: {
      menuKeys: ['downloadAttachment'], // “下载附件”菜单
    },
  },
  // TS 语法
  MENU_CONF: {
    uploadAttachment: {
      server: 'https://airport.dingyangmy.cn/prod-api/file/uploadRichText', // 服务端地址
      timeout: 5 * 1000, // 5s

      fieldName: 'custom-fileName',
      // meta: {token: 'xxx', a: 100}, // 请求时附加的数据
      metaWithUrl: true, // meta 拼接到 url 上
      headers: {Accept: 'text/x-json'},

      maxFileSize: 10 * 1024 * 1024, // 10M

      onBeforeUpload(file: File) {
        console.log('onBeforeUpload', file)
        return file // 上传 file 文件
        // return false // 会阻止上传
      },
      onProgress(progress: number) {
        console.log('onProgress', progress)
      },
      onSuccess(file: File, res: any) {
        console.log('onSuccess', file, res)
      },
      onFailed(file: File, res: any) {
        alert(res.message)
        console.log('onFailed', file, res)
      },
      onError(file: File, err: Error, res: any) {
        alert(err.message)
        console.error('onError', file, err, res)
      },
    },

    uploadImage: {
      // 上传接口地址，必须是完整地址（你本地 Node 服务地址）
      server: 'https://airport.dingyangmy.cn/prod-api/file/uploadImage', // 服务端地址

      // 后端接收的字段名，对应 `formidable` 接收的字段
      fieldName: 'file',

      // 文件限制
      maxFileSize: 2 * 1024 * 1024, // 2MB
      allowedFileTypes: ['image/*'],

      // 设置 headers 和跨域选项（如果需要）
      headers: {
        Accept: 'application/json'
      },
      withCredentials: false,

      // 上传成功后的处理（可选）
      onSuccess(file, res) {
        console.log('上传成功:', res)
      },

      onFailed(file, res) {
        console.error('上传失败:', res)
      },

      onError(file, err, res) {
        console.error('上传出错:', err)
      },
    }
  }
}

export const toolbarConfig: Partial<IToolbarConfig> = {  // TS 语法
  // 插入哪些菜单
  insertKeys: {
    index: 0, // 自定义插入的位置
    keys: ['uploadAttachment'], // “上传附件”菜单
  },

}

export const mobileToolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: [
    'blockquote',
    'bulletedList',
    'numberedList',
    'todo',
    'group-justify',
    'group-indent',
    'emotion',
    'insertLink',
    'group-video',
    'group-image',
    'divider',
    'fullScreen',
    'lineHeight',
    'group-more-style',
    'undo',
    'redo',
    'codeBlock'
  ],
  // 插入哪些菜单
  insertKeys: {
    index: 0, // 自定义插入的位置
    keys: ['uploadAttachment'], // “上传附件”菜单
  },
}


export const viewEditorConfig: Partial<IEditorConfig> = {
  readOnly: true,
  hoverbarKeys: {
    attachment: {
      menuKeys: ['downloadAttachment'], // “下载附件”菜单
    },
  },
  // TS 语法
  MENU_CONF: {
    uploadAttachment: {
      server: 'https://airport.dingyangmy.cn/prod-api/file/uploadRichText', // 服务端地址
      timeout: 5 * 1000, // 5s

      fieldName: 'custom-fileName',
      // meta: {token: 'xxx', a: 100}, // 请求时附加的数据
      metaWithUrl: true, // meta 拼接到 url 上
      headers: {Accept: 'text/x-json'},

      maxFileSize: 10 * 1024 * 1024, // 10M

      onBeforeUpload(file: File) {
        console.log('onBeforeUpload', file)
        return file // 上传 file 文件
        // return false // 会阻止上传
      },
      onProgress(progress: number) {
        console.log('onProgress', progress)
      },
      onSuccess(file: File, res: any) {
        console.log('onSuccess', file, res)
      },
      onFailed(file: File, res: any) {
        alert(res.message)
        console.log('onFailed', file, res)
      },
      onError(file: File, err: Error, res: any) {
        alert(err.message)
        console.error('onError', file, err, res)
      },
    },

    uploadImage: {
      // 上传接口地址，必须是完整地址（你本地 Node 服务地址）
      server: 'https://airport.dingyangmy.cn/prod-api/file/uploadImage', // 服务端地址

      // 后端接收的字段名，对应 `formidable` 接收的字段
      fieldName: 'file',

      // 文件限制
      maxFileSize: 10 * 1024 * 1024, // 2MB
      // allowedFileTypes: ['image/*'],

      // 设置 headers 和跨域选项（如果需要）
      headers: {
        Accept: 'application/json'
      },
      withCredentials: false,

      // 上传成功后的处理（可选）
      onSuccess(file, res) {
        console.log('上传成功:', res)
      },

      onFailed(file, res) {
        console.error('上传失败:', res)
      },

      onError(file, err, res) {
        console.error('上传出错:', err)
      },
    }
  }
}

